﻿using AutoMapper;
using MediatR;
using RedDragon.Common.Domain.MaterialManagements;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using SqlSugar;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.MaterialManagements
{
    /// <summary>
    /// 物料类别显示Handler
    /// </summary>
    public class SearchMaterialCategoryHandler : IRequestHandler<SearchMaterialCategoryCommand, Result>
    {
        private readonly ISqlSugarClient _db;
        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 物料类别表仓储
        /// </summary>
        public readonly IBaseRepository<MaterialCategory> materialCategoryrepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchMaterialCategoryHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="materialCategoryrepository"></param>
        /// <param name="logger"></param>
        /// <param name="db"></param>
        public SearchMaterialCategoryHandler(IMapper mapper, IBaseRepository<MaterialCategory> materialCategoryrepository, ILogger<SearchMaterialCategoryHandler> logger, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.materialCategoryrepository = materialCategoryrepository;
            this.logger = logger;
            _db = db;
        }
        /// <summary>
        /// 物料类别
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(SearchMaterialCategoryCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                var tree = await (await materialCategoryrepository.GetAll()).ToTreeAsync(it => it.Children, it => it.PId, 0);
                //判断获取的数据不为空
                if (tree.Count > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = tree;
                    result.Msg = "物料类别树形显示成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "物料类别树形显示异常" + ex.Message;
                logger.LogError("物料类别树形显示异常" + ex.Message);
            }
            return result;
        }
    }
}
